package com.gin.no_gay_alliance.database.where;

import android.os.Parcel;
import android.os.Parcelable;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.sqlite.db.SimpleSQLiteQuery;

import com.gin.common.utils.TimeUtils;
import com.gin.jackson.utils.ObjectUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 回复历史的where子句参数对象
 *
 * @author : ginstone
 * @version : v1.0.0
 * @since : 2023/9/18 15:15
 **/
public class ReplyHistoryWhere implements SqlWhere, Parcelable, Cloneable {
    public static final int LOGIC_AND = 0;
    public static final int LOGIC_OR = 1;
    public static final Creator<ReplyHistoryWhere> CREATOR = new Creator<ReplyHistoryWhere>() {
        @Override
        public ReplyHistoryWhere createFromParcel(Parcel in) {
            return new ReplyHistoryWhere(in);
        }

        @Override
        public ReplyHistoryWhere[] newArray(int size) {
            return new ReplyHistoryWhere[size];
        }
    };
    private static final String TAG = ReplyHistoryWhere.class.getSimpleName();
    /**
     * 发布时间(起)
     */
    public Long start;
    /**
     * 发布时间(止)
     */
    public Long end;
    /**
     * 用户名关键字
     */
    public String username;
    /**
     * 正文关键字
     */
    public String keyword;
    /**
     * 多个关键字时的相互关系
     */
    public int logic = LOGIC_AND;
    /**
     * 是否含有 [img] 代码
     */
    public Boolean hasImage;

    public ReplyHistoryWhere() {
    }

    protected ReplyHistoryWhere(Parcel in) {
        if (in.readByte() == 0) {
            start = null;
        } else {
            start = in.readLong();
        }
        if (in.readByte() == 0) {
            end = null;
        } else {
            end = in.readLong();
        }
        username = in.readString();
        keyword = in.readString();
        logic = in.readInt();
        byte tmpHasImage = in.readByte();
        hasImage = tmpHasImage == 0 ? null : tmpHasImage == 1;
    }

    /**
     * 生成条件描述
     *
     * @return 条件描述
     */
    public String buildDescription() {
        StringBuilder sb = new StringBuilder();
        sb.append("关键字逻辑: ").append(logic == LOGIC_AND ? "且" : "或").append("; ");
        if (start != null) {
            sb.append("发布时间(起): ").append(TimeUtils.format(start, TimeUnit.SECONDS, TimeUtils.SHORT_FORMATTER)).append("; ");
        }
        if (end != null) {
            sb.append("发布时间(止): ").append(TimeUtils.format(end, TimeUnit.SECONDS, TimeUtils.SHORT_FORMATTER)).append("; ");
        }
        if (!ObjectUtils.isEmpty(username)) {
            sb.append("用户名包含: ").append(username).append("; ");
        }
        if (hasImage != null) {
            sb.append(hasImage ? "包含图片; " : "不含图片; ");
        }
        return sb.toString();
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        if (start == null) {
            dest.writeByte((byte) 0);
        } else {
            dest.writeByte((byte) 1);
            dest.writeLong(start);
        }
        if (end == null) {
            dest.writeByte((byte) 0);
        } else {
            dest.writeByte((byte) 1);
            dest.writeLong(end);
        }
        dest.writeString(username);
        dest.writeString(keyword);
        dest.writeInt(logic);
        dest.writeByte((byte) (hasImage == null ? 0 : hasImage ? 1 : 2));
    }

    /**
     * 生成where子句
     *
     * @return where子句
     */
    @Override
    public SimpleSQLiteQuery buildSql(String template) {
        StringBuilder whereBuilder = new StringBuilder("1=1");
        List<Object> args = new ArrayList<>();

        if (start != null) {
            whereBuilder.append(" and postDatetime>=:start");
            args.add(start);
        }
        if (end != null) {
            whereBuilder.append(" and postDatetime<=:end");
            args.add(end);
        }
        if (!ObjectUtils.isEmpty(username)) {
            whereBuilder.append(" and username like '%' || :username || '%'");
            args.add(username);
        }
        if (!ObjectUtils.isEmpty(keyword)) {
            //逻辑默认为 and
            // 关键字列表
            List<String> keywordList = Arrays.stream(keyword.split(" "))
                    .filter(i -> !ObjectUtils.isEmpty(i))
                    .collect(Collectors.toList());

            // 拼接关键字like条件
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < keywordList.size(); i++) {
                if (i > 0) {
                    sb.append(logic == LOGIC_AND ? " and " : " or ");
                }
                sb.append("content like '%' || :").append("k").append(i).append(" || '%'");
                args.add(keywordList.get(i));
            }
            // 拼接关键字条件整合
            whereBuilder.append(String.format(" and (%s)", sb));
        }
        if (hasImage != null) {
            if (hasImage) {
                whereBuilder.append(" and content like '%' || :img || '%'");
            } else {
                whereBuilder.append(" and content not like '%' || :img || '%'");
            }
            args.add("[img]");
        }

        String sql = String.format(Locale.CHINA, template, whereBuilder);
        Log.d(TAG, "[SQL]: " + sql);
        Log.d(TAG, "[PARAMS]: " + args);
        return new SimpleSQLiteQuery(sql, args.toArray());
    }

    @NonNull
    @Override
    public ReplyHistoryWhere clone() {
        try {
            return (ReplyHistoryWhere) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new AssertionError();
        }
    }
}
